package com.zyd.service.station.impl;

import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.zyd.config.StationStatusConfig;
import com.zyd.constants.ErrorDef;
import com.zyd.exception.BusinessException;
import com.zyd.io.model.RolePowerEntity;
import com.zyd.io.model.StationEntity;
import com.zyd.io.model.StationEntityExample;
import com.zyd.io.model.StationEntityKey;
import com.zyd.io.vo.page.MultiQueryPageVO;
import com.zyd.io.page.PageBean;
import com.zyd.mappers.StationEntityMapper;
import com.zyd.service.power.PowerService;
import com.zyd.service.station.StationService;
import com.zyd.util.SqlUtils;
import com.zyd.util.StringUtils;
import com.zyd.util.ToolUtils;
import com.zyd.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import com.zyd.context.HeaderContext;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@Component
public class StationServiceImpl implements StationService {
    private static final Splitter SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();
    @Autowired
    private StationStatusConfig stationStatusConfig;

    @Autowired
    private StationEntityMapper mapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PowerService powerService;

    @Override
    public PageBean<StationEntity> findStationPage(MultiQueryPageVO request) {
        String countSql = "SELECT count(*)";
        String selectFields = "SELECT * ";
        //查询最近的基站运行状态记录，与基站表关联
        StringBuilder sql = new StringBuilder();
        sql.append(" from zydzn_station WHERE dr=0 ");
        sql.append(SqlUtils.addMultiCondition(request.getSearchKeys()));


        RolePowerEntity rolePowerEntity = powerService.queryPowerListByUserId((String) HeaderContext.get().get("userid"), "2010");
        if (rolePowerEntity != null) {
            //非空验证 为了防止地区为配置 sql报错  这里就是如果没配置 会全查
            if (SqlUtils.addIn(rolePowerEntity.getArea()) != null && !SqlUtils.addIn(rolePowerEntity.getArea()).equals("")) {
                sql.append(" and area in (" + SqlUtils.addIn(rolePowerEntity.getArea()) + ")");
            } else {
                return null;
            }
        } else {
            sql.append(" and area in ('10000')");
        }

        Long totalRows = jdbcTemplate.queryForObject(countSql + sql.toString(), Long.class);
        String pageSql = SqlUtils.addPage(selectFields + sql.toString(), request.getCurrentPage(), request.getPageSize());

        List<StationEntity> ret = jdbcTemplate.query(pageSql, new RowMapper<StationEntity>() {

            @Override
            public StationEntity mapRow(ResultSet rs, int rowNum) throws SQLException {
                StationEntity stationEntity = SqlUtils.mappingToBean(rs, StationEntity.class);
                return stationEntity;
            }
        });

        PageBean<StationEntity> pageBean = new PageBean<StationEntity>(request.getCurrentPage(), request.getPageSize(), totalRows.intValue());
        pageBean.setItems(ret);
        return pageBean;
    }

    @Override
    public StationEntity findStation(String id) {
        StationEntityKey key = new StationEntityKey();
        key.setId(id);
        return mapper.selectByPrimaryKey(key);
    }

    @Override
    public void addStation(StationEntity station) {
        station.setId(UUIDUtil.getUUid());

        checkDataValidation(station);
        checkValid(station);

        station.setRegtime(ToolUtils.getNowTime());
        station.setStationstatus("不正常");
        station.setTs(ToolUtils.getNowTime());
        station.setDr(0);

        mapper.insertSelective(station);
    }

    @Override
    public void updateStation(StationEntity station) {
        checkDataValidation(station);

        station.setTs(ToolUtils.getNowTime());
        //checkValid(station);
        mapper.updateByPrimaryKeySelective(station);
    }

    @Override
    public void deleteStation(String id) {
        StationEntity stationEntity = new StationEntity();
        stationEntity.setId(id);
        stationEntity.setDr(1);
        stationEntity.setTs(ToolUtils.getNowTime());
        mapper.updateByPrimaryKeySelective(stationEntity);
    }

    @Override
    public List<StationEntity> findStationList(String userid) {
        //StationEntityExample example = new StationEntityExample();
        //example.or().andDrEqualTo(0);
        //return mapper.selectByExample(example);
        String selectFields = "SELECT * ";
        //查询最近的基站运行状态记录，与基站表关联
        StringBuilder sql = new StringBuilder();
        sql.append(" from zydzn_station WHERE dr=0 ");
        System.out.println(userid);

        RolePowerEntity rolePowerEntity = powerService.queryPowerListByUserId(userid, "2010");
        System.out.println(rolePowerEntity);

        if (rolePowerEntity != null) {
            //非空验证 为了防止地区为配置 sql报错  这里就是如果没配置 会全查
            if (SqlUtils.addIn(rolePowerEntity.getArea()) != null && !SqlUtils.addIn(rolePowerEntity.getArea()).equals("")) {
                sql.append(" and area in (" + SqlUtils.addIn(rolePowerEntity.getArea()) + ")");
            } else {
                return null;
            }
        } else {
            sql.append(" and area in ('10000')");
        }
        System.out.println(sql);

        List<StationEntity> ret = jdbcTemplate.query(selectFields + sql.toString(), new RowMapper<StationEntity>() {

            @Override
            public StationEntity mapRow(ResultSet rs, int rowNum) throws SQLException {
                StationEntity stationEntity = SqlUtils.mappingToBean(rs, StationEntity.class);
                return stationEntity;
            }
        });
        return ret;

    }

    @Override
    public List<Map<String, Object>> findStationCount(Map<String, Object> request) {
        isNullVerify(request);

        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT a.address,a.jd,a.wd,a.stationcode,a.stationname,a.stationstatus,(case when tb.num  is null then 0 else  tb.num end) num  ");

        sql.append("  from zydzn_station a   LEFT JOIN ( SELECT base_id ,sum(num) as num from ((SELECT base_id ,count(base_id) AS num  ");
        sql.append("  FROM socket_now  where  rec_time between   ");
        sql.append(" DATE_FORMAT('" + request.get("starTime") + "', '%Y-%m-%d %H:%i:%s') ");

        sql.append("  and DATE_FORMAT('" + request.get("endTime") + "', '%Y-%m-%d %H:%i:%s') ");
        sql.append("  and tag_id is not NULL and tag_id <>'' GROUP BY base_id) ");
        sql.append("  union all  (SELECT base_id ,count(base_id) AS num FROM socket_history_thirty where  ");
        sql.append("  rec_time between   ");
        sql.append(" DATE_FORMAT('" + request.get("starTime") + "', '%Y-%m-%d %H:%i:%s') ");

        sql.append("  and DATE_FORMAT('" + request.get("endTime") + "', '%Y-%m-%d %H:%i:%s') ");
        sql.append("  and tag_id is not NULL and tag_id <>'' GROUP BY base_id) ");
        sql.append(" ) as tt GROUP BY tt.base_id  ) as tb ");
        sql.append("  on  a.stationcode=tb.base_id  ");
        sql.append("  where a.dr=0   ");
        RolePowerEntity rolePowerEntity = powerService.queryPowerListByUserId((String) HeaderContext.get().get("userid"), "2010");
        System.out.println(rolePowerEntity);
        if (rolePowerEntity != null) {
            //非空验证 为了防止地区为配置 sql报错  这里就是如果没配置 会全查
            if (SqlUtils.addIn(rolePowerEntity.getArea()) != null && !SqlUtils.addIn(rolePowerEntity.getArea()).equals("")) {
                sql.append(" and area in (" + SqlUtils.addIn(rolePowerEntity.getArea()) + ")");
            } else {
                return null;
            }
        } else {
            sql.append(" and area in ('10000')");
        }
        return jdbcTemplate.query(sql.toString(), new RowMapper<Map<String, Object>>() {
            @Override
            public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
                Map ret = Maps.newHashMap();
                ret.put("address", rs.getString("address"));
                ret.put("jd", rs.getString("jd"));
                ret.put("wd", rs.getString("wd"));
                ret.put("stationcode", rs.getString("stationcode"));
                ret.put("stationname", rs.getString("stationname"));
                ret.put("stationstatus", rs.getString("stationstatus"));
                ret.put("num", rs.getInt("num"));
                return ret;
            }
        });

    }

    private void checkValid(StationEntity station) {
        StationEntityExample entityExample = new StationEntityExample();
        entityExample.or().andStationidEqualTo(station.getStationid()).andDrEqualTo(0);
        List<StationEntity> ret = mapper.selectByExample(entityExample);

        if (ret.size() > 0 && !ret.get(0).getStationid().equals(station.getStationid())) {
            throw new BusinessException(ErrorDef.SYSTEM_ERROR, "基站ID重复!");
        }

        entityExample = new StationEntityExample();
        entityExample.or().andStationcodeEqualTo(station.getStationcode()).andDrEqualTo(0);
        ret = mapper.selectByExample(entityExample);
        if (ret.size() > 0 && !ret.get(0).getStationcode().equals(station.getStationcode())) {
            throw new BusinessException(ErrorDef.SYSTEM_ERROR, "基站编号重复!");
        }
    }

    private String checkErrorMsg(StationEntity station) {
        String errmsg = "";
        if (StringUtils.isEmpty(station.getStationname())) {
            errmsg = "基站名称不能为空!";
            return errmsg;
        } else if (StringUtils.isEmpty(station.getStationid())) {
            errmsg = "基站ID不能为空!";
            return errmsg;
        } else if (StringUtils.isEmpty(station.getStationcode())) {
            errmsg = "基站编号不能为空!";
            return errmsg;
        } else if (StringUtils.isEmpty(station.getAddress())) {
            errmsg = "基站地址不能为空!";
            return errmsg;
        } else if (StringUtils.isEmpty(station.getJd())) {
            errmsg = "经度不能为空!";
            return errmsg;
        } else if (StringUtils.isEmpty(station.getWd())) {
            errmsg = "维度不能为空!";
            return errmsg;
        }
        return errmsg;
    }

    private void checkDataValidation(StationEntity station) {
        String validation = checkErrorMsg(station);
        if (StringUtils.isNotBlank(validation)) {
            throw new BusinessException(ErrorDef.SYSTEM_ERROR, validation);
        }
    }
//    非空判断校验

    public void isNullVerify(Map<String, Object> request) {
        if (request.get("startTime") == null || request.get("startTi").equals("")) {
            request.put("startTime", 0);
        }
        if (request.get("endTime") == null || request.get("endTime").equals("")) {
            request.put("endTime", "now()");
        }

    }

    //基站分布查询
    @Override
    public List<StationEntity> findStationAll(Map<String, Object> request) {

        RolePowerEntity rolePowerEntity = powerService.queryPowerListByUserId((String) HeaderContext.get().get("userid"), "3010");
        if (rolePowerEntity != null) {//如果查询的权限实体不为空
            StationEntityExample example = new StationEntityExample();
            StationEntityExample.Criteria criteria = example.createCriteria();
            criteria.andDrEqualTo(0);
            String area = rolePowerEntity.getArea();
            if (!org.springframework.util.StringUtils.isEmpty(area)) {//area不为空
                List<String> areaList = SPLITTER.splitToList(area);
                //构建对应的查询条件
                criteria.andAreaIn(areaList);
            }
            return mapper.selectByExample(example);
        }
        return null;
    }

    @Override
    public List<StationEntity> findStationList(MultiQueryPageVO request, String userid) {

        String selectFields = "SELECT * ";
        //查询最近的基站运行状态记录，与基站表关联
        StringBuilder sql = new StringBuilder();
        sql.append(" from zydzn_station WHERE dr=0 ");
        sql.append(SqlUtils.addMultiCondition(request.getSearchKeys()));

        RolePowerEntity rolePowerEntity = powerService.queryPowerListByUserId(userid, "2010");
        if (rolePowerEntity != null) {
            if (SqlUtils.addIn(rolePowerEntity.getArea()) != null && !SqlUtils.addIn(rolePowerEntity.getArea()).equals("")) {
                sql.append(" and area in (" + SqlUtils.addIn(rolePowerEntity.getArea()) + ")");
            } else {
                return null;
            }
        } else {
            sql.append(" and area in ('10000')");
        }
        List<StationEntity> ret = jdbcTemplate.query(selectFields + sql.toString(), (rs, rowNum) -> {
            StationEntity stationEntity = SqlUtils.mappingToBean(rs, StationEntity.class);
            return stationEntity;
        });


        return ret;
    }

}
